package cc.telecomdigital.tdstock.activity.groups.monitor.util;

import java.util.List;

import android.app.Activity;
import android.content.Context;
import android.os.AsyncTask;
import android.os.ConditionVariable;
import android.view.View;
import cc.telecomdigital.tdstock.CommonDefn;
import cc.telecomdigital.tdstock.CustomizeDialog;
import cc.telecomdigital.tdstock.R;
import cc.telecomdigital.tdstock.SystemInfo;
import cc.telecomdigital.tdstock.Framework.UniqueItem.TDStockLog;
import cc.telecomdigital.tdstock.Http.H_CODE;
import cc.telecomdigital.tdstock.Http.Services.HttpAppInfo;
import cc.telecomdigital.tdstock.Http.Services.H_HttpServiceRequest.H_UserClient_HttpRequest_Result;
import cc.telecomdigital.tdstock.Http.Services.H_HttpServiceRequest.IH_UserClient_HttpRequest_Report;
import cc.telecomdigital.tdstock.activity.BMPBaseActivity;
import cc.telecomdigital.tdstock.activity.BaseActivity;

public class SaveBookMarkAsyncTask extends AsyncTask<String, String, String>
	implements IH_UserClient_HttpRequest_Report
{
	private final static String	TAG			= SaveBookMarkAsyncTask.class
												.getSimpleName();

	private BookMarkInterface	bookMarkInterface;
	private String				itemCode;
	private int				type;
	private Context			context;
	private String				_current_stock_chinese_short_name;
	private List<String[]>		portfolioActivityItems;
	private String				saveResult	= MonitorUtil.DEFAULTRESULT;

	// 用于单个保存
	public SaveBookMarkAsyncTask(String itemCode, int type, Context context,
			BookMarkInterface bookMarkInterface,
			String _current_stock_chinese_short_name)
	{
		super();
		this.itemCode = itemCode;
		this.type = type;
		this.context = context;
		this.bookMarkInterface = bookMarkInterface;
		this._current_stock_chinese_short_name = _current_stock_chinese_short_name;
		this.portfolioActivityItems = null;
	}

	// 用于监察表编辑多个保存
	public SaveBookMarkAsyncTask(Context context,
			BookMarkInterface bookMarkInterface,
			String _current_stock_chinese_short_name, List<String[]> items)
	{
		super();
		this._current_stock_chinese_short_name = _current_stock_chinese_short_name;
		this.context = context;
		this.bookMarkInterface = bookMarkInterface;
		this.itemCode = null;
		this.portfolioActivityItems = items;
	}

	@Override
	protected String doInBackground(String... params)
	{
		TDStockLog.d(TAG, TAG + "------------->doInBackground");

		if (!SystemInfo.isNetworkingConnected(context))
		{
			return MonitorUtil._IS_NET_ERROR;
		}
		SendHttpServiceRequest(context);
		return null;
	}

	/*@Override
	protected String doInBackground(String... params)
	{
		String saveResult = MonitorUtil.DEFAULTRESULT;
		String uploadResult = MonitorUtil.DEFAULTRESULT;

		if (!SystemInfo.isNetworkingConnected(context))
		{
			return MonitorUtil._IS_NET_ERROR;
		}
		List<String[]> items = bookMarkInterface.getItems(context);
		if (items == null)
		{
			return MonitorUtil._IS_NET_ERROR;
		}
		// 用于单个保存
		if (null != itemCode && !"".equals(itemCode))
		{
			
			saveResult = bookMarkInterface.addBookMarkItem(items, itemCode,
					type, context);
			if (MonitorUtil._ADD_SUCCESS.equalsIgnoreCase(saveResult))
			{
				StringBuffer item = MonitorUtil.getInstance().getItem(
						MonitorUtil.items);
				StringBuffer type = MonitorUtil.getInstance().getType(
						MonitorUtil.items);

				uploadResult = MonitorUtil.getInstance()
						.upLoadBookMarksToServer(item, type, context);
			}
		}
		// 用于监察表编辑多个保存
		else if (portfolioActivityItems != null)
		{
			if (MonitorUtil.isUpdated(items, portfolioActivityItems))
			{
				StringBuffer item = MonitorUtil.getInstance().getItem(
						portfolioActivityItems);
				StringBuffer type = MonitorUtil.getInstance().getType(
						portfolioActivityItems);
				uploadResult = MonitorUtil.getInstance()
						.upLoadBookMarksToServer(item, type, context);
			}
			else
			{

			}
		}
		return saveResult + "," + uploadResult;
	}*/

//	@Override
//	protected void onPostExecute(String result)
//	{
//		super.onPostExecute(result);
//		if (null == result)
//		{
//			return;
//		}
//		//TDStockLog.d(TAG, result);
//		//disposal_Save_Result(result, _current_stock_chinese_short_name);
//	}

	// 处理上传结果 Disposal Upload Result
	public void disposal_Upload_Result(String status,
			String _current_stock_chinese_short_name)
	{
		TDStockLog.d(TAG, status == null ? "status is null" : status);
		if (status != null && !"".equals(status))
		{
			// upload failre
			if (status.startsWith(MonitorUtil.UPLOADFAILURE))
			{
				new CustomizeDialog(MonitorUtil.getInstance()
						.getMyOwnContext(context), "", context
						.getResources().getString(R.string.addfailure))
						.show();
			}
			else if (status.startsWith(MonitorUtil.UPLOADSUCCESS))
			{
				String[] results = status.split("&");
				// the sucess
				if ("0".equalsIgnoreCase(results[1]))
				{
					// _current_stock_chinese_short_name="" 在监察表UI时保存
					// _current_stock_chinese_short_name！="" 在其他子UI单条添加时
					if (!"".equals(_current_stock_chinese_short_name)
							&& null != _current_stock_chinese_short_name)
					{
						if (context instanceof BaseActivity)
						{
							BaseActivity ba = (BaseActivity) context;
							ba.startAnimat(_current_stock_chinese_short_name);
						}
						else if (context instanceof BMPBaseActivity)
						{
							BMPBaseActivity bmpba = (BMPBaseActivity) context;
							bmpba.startAnimat(_current_stock_chinese_short_name);
						}
/*						new CustomizeDialog(MonitorUtil.getInstance()
								.getMyOwnContext(context), "", context
								.getResources().getString(
										R.string.monitor_add_to))
								.show();*/
					}
					else
					{
						/*
						 * new CustomizeDialog(
						 * MonitorUtil.getInstance().getMyOwnContext(context),
						 * "",
						 * context.getResources().getString(R.string.monitor_edit_s
						 * )).show();
						 */
					}

					// update bookmark number
					// MonitorUtil.getInstance().updateBookMarkNumber(context);
					// }
				}
				// the not update
				else if ("1".equalsIgnoreCase(results[1]))
				{
					new CustomizeDialog(MonitorUtil.getInstance()
							.getMyOwnContext(context), "", context
							.getResources().getString(
									R.string.monitor_exist_stock))
							.show();
				}
				// the fail
				else if ("-1".equalsIgnoreCase(results[1]))
				{
					new CustomizeDialog(MonitorUtil.getInstance()
							.getMyOwnContext(context), "", context
							.getResources().getString(
									R.string.addfailureonserver))
							.show();
				}
			}
		}
	}

	public void disposal_Save_Result(String result,
			String _current_stock_chinese_short_name)
	{
		// add sucess or bookmark delete and desc
		if (result.startsWith(MonitorUtil._ADD_SUCCESS)
				|| (result.startsWith(MonitorUtil.DEFAULTRESULT) && !result
						.endsWith(MonitorUtil.DEFAULTRESULT)))
		{
			String[] temp = result.split(",");
			disposal_Upload_Result(temp[1],
					_current_stock_chinese_short_name);
		}
		// bookmark full
		else if (result.startsWith(MonitorUtil._IS_FULL))
		{
			/*
			 * new CustomizeDialog(getMyOwnContext(context), "",
			 * context.getResources
			 * ().getString(R.string.monitor_is_full_with_items)).show();
			 */
			new CustomizeDialog(MonitorUtil.getInstance().getMyOwnContext(
					context), "", context.getResources().getString(
					R.string.monitor_is_full_with_items)).show();
		}
		// bookmark presence
		else if (result.startsWith(MonitorUtil._IS_PRESENCE))
		{

			String tips = context.getResources().getString(
					R.string.monitor_exist_others);
			final int stockType = CommonDefn.BookMarkType.stock
					.getBookMarkType();
			final int indexType = CommonDefn.BookMarkType.index
					.getBookMarkType();
			if (this.type == stockType)
			{
				tips = context.getResources().getString(
						R.string.monitor_exist_stock);
			}
			else if (this.type == indexType)
			{
				tips = context.getResources().getString(
						R.string.monitor_exist_index);
			}

			new CustomizeDialog(MonitorUtil.getInstance().getMyOwnContext(
					context), "", tips).show();
		}
		// net error
		else if (result.startsWith(MonitorUtil._IS_NET_ERROR))
		{
			/*
			 * new CustomizeDialog(getMyOwnContext(context), "",
			 * context.getResources().getString(R.string.net_error)).show();
			 */
			new CustomizeDialog(MonitorUtil.getInstance().getMyOwnContext(
					context), "", context.getResources().getString(
					R.string.net_error)).show();
		}
	}

	static private ConditionVariable	retryLogonConnection;

	private H_CODE SendHttpServiceRequest_Save(Context iContext,
			StringBuffer item, StringBuffer type)
	{
		H_CODE statusCode;
		statusCode = HttpAppInfo.SaveBookMark(iContext, item, type, this,
				"Req-2");
		return statusCode;
	}

	/* (non-Javadoc)
	 * @see cc.telecomdigital.tdstock.Http.Services.H_HttpServiceRequest.IH_UserClient_HttpRequest_Report#H_UserClient_HttpRequest_Response(cc.telecomdigital.tdstock.Http.Services.H_HttpServiceRequest.H_UserClient_HttpRequest_Result)
	 */
	@Override
	public void H_UserClient_HttpRequest_Response(
			H_UserClient_HttpRequest_Result iResult)
	{
		TDStockLog.d(TAG, TAG
				+ "--->H_UserClient_HttpRequest_Response--->status--->"
				+ iResult.MStatus);

		if (!iResult.MStatus.equals("0"))
		{
			// show error message.
			ShowMessageDialog(iResult.MError + "(" + iResult.MStatus + ")");
			return;
		}
		TDStockLog.d(TAG, "seqID---------->" + iResult.seqID);
		if ("Req-1".equals(iResult.seqID))
		{
			retryLogonConnection.open();
			// callback..
			List<String[]> items = iResult.contentStores;
			TDStockLog.d(TAG,
					"items size---->" + (items != null ? items.size() : 0));
			TDStockLog.d(TAG, "itemCode-------->"
					+ (itemCode == null ? "" : itemCode));
			// 用于单个保存
			if (null != itemCode && !"".equals(itemCode))
			{
				H_UserClient_HttpRequest_Response_Stub_GetBookMark(items);
			}
			// 用于监察表编辑多个保存
			else if (portfolioActivityItems != null)
			{
				H_UserClient_HttpRequest_Response_Stub_SaveBookMark(items);
			}

		}
		else if ("Req-2".equals(iResult.seqID))
		{
			String uploadresult = iResult.contentStores.get(0)[0];
			TDStockLog.d(TAG, "uploadresult------>"+ (uploadresult == null ? "uploadresult  is  null" : uploadresult));
			String result = saveResult;
			if (uploadresult == null)
			{
				uploadresult = MonitorUtil.UPLOADFAILURE + "&" + "result";
			}
			else
			{
				uploadresult = MonitorUtil.UPLOADSUCCESS + "&"
						+ uploadresult;
			}
			result = result + "," + uploadresult;
			TDStockLog.d(TAG, result == null ? "" : result);
			disposal_Save_Result(result, _current_stock_chinese_short_name);

		}
	}

	private void H_UserClient_HttpRequest_Response_Stub_GetBookMark(List<String[]> items){
		saveResult = bookMarkInterface.addBookMarkItem(items,
				itemCode, type, context);
		if (MonitorUtil._ADD_SUCCESS.equalsIgnoreCase(saveResult))
		{
			StringBuffer item = MonitorUtil.getInstance().getItem(
					MonitorUtil.items);
			StringBuffer type = MonitorUtil.getInstance().getType(
					MonitorUtil.items);

			SendHttpServiceRequest_Save(context, item, type);
		}
		else
		{
			disposal_Save_Result(saveResult,
					_current_stock_chinese_short_name);
		}
	}
	
	
	private void H_UserClient_HttpRequest_Response_Stub_SaveBookMark(List<String[]> items){
		if (MonitorUtil.isUpdated(items, portfolioActivityItems))
		{
			StringBuffer item = MonitorUtil.getInstance().getItem(
					portfolioActivityItems);
			StringBuffer type = MonitorUtil.getInstance().getType(
					portfolioActivityItems);
			SendHttpServiceRequest_Save(context, item, type);
		}
	}
	
	
	
	private H_CODE SendHttpServiceRequest(Context iContext)
	{
		TDStockLog.d(TAG, TAG
				+ "------------->SendHttpServiceRequest");
		H_CODE statusCode;

		if (retryLogonConnection == null)
			retryLogonConnection = new ConditionVariable();

		statusCode = HttpAppInfo.GetBookMark(iContext, this, "Req-1");
		if (statusCode == H_CODE.OK || statusCode == H_CODE.SYSTEM_BUSY)
		{
			retryLogonConnection.block(CommonDefn.CONNECTION_TIMEOUT*20);
		}
		return statusCode;
	}
	

	private void ShowMessageDialog(String msgContent)
	{
		if(context instanceof Activity){
			Activity activity=(Activity)context;
			CustomizeDialog promptBox;
			promptBox = new CustomizeDialog(activity.getParent()==null?activity:activity.getParent(), "提示",
					msgContent)
			{
				@Override
				public void onClick(View v)
				{
					dismissAll();
				}
			};
			promptBox.setCancelable(true);
			promptBox.show();
		}

	}
}
